<template>
	<a-modal
		:title="title"
		:width="modalWidth"
		:bodyStyle="bodyStyle"
		:visible="visible"
		:confirmLoading="confirmLoading"
		@ok="handleOk"
		@cancel="handleCancel"
		:destroyOnClose="true"
		:maskClosable="false"
	>
		<a-spin :spinning="confirmLoading">
			<a-form :form="form" autocomplete="off" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<a-form-item label="活动名称">
					<a-input
						placeholder="活动名称"
						v-decorator="[
							'activityName',
							{
								rules: [{ required: true, whitespace: true, message: '活动名称' }],
								getValueFromEvent: removeSpaces
							}
						]"
					/>
				</a-form-item>
				<a-form-item label="音乐链接">
					<div><audio controls="controls" v-if="musicUrl" :src="filebaseUrl + musicUrl">当前浏览器不支持audio</audio></div>
					<a-upload
						v-decorator="[
							'musicUrl',
							{
								valuePropName: 'file',
								getValueFromEvent: normMusiFile,
								rules: [{ required: true, message: '音乐链接' }]
							}
						]"
						name="file"
						:action="uploadFile"
						:show-upload-list="false"
						class="avatar-uploader"
						:headers="headers"
					>
						<a-button>
							<a-icon :type="loadingMusic ? 'loading' : 'upload'" />
							{{ musicUrl ? '替换音乐' : '上传音乐' }}
						</a-button>
					</a-upload>
				</a-form-item>
				<a-form-item label="活动时间">
					<a-range-picker
						allowClear
						v-decorator="[
							'activityTime',
							{
								rules: [{ required: true, message: '活动时间' }]
							}
						]"
						class="w100"
					/>
				</a-form-item>
				<a-form-item label="联系方式">
					<a-input
						class="w100"
						placeholder="联系方式"
						:visibilityToggle="false"
						v-decorator="[
							'telPhone',
							{
								rules: [
									{ required: true, message: '联系方式' },
									{
										pattern: /^1[3-9]\d{9}$/,
										message: '请输入联系方式'
									}
								]
							}
						]"
					/>
				</a-form-item>
				<a-form-item label="活动封面">
					<a-upload
						v-decorator="[
							'coverImg',
							{
								valuePropName: 'file',
								getValueFromEvent: normFile,
								rules: [{ required: true, message: '活动封面' }]
							}
						]"
						name="file"
						:action="uploadFile"
						:show-upload-list="false"
						list-type="picture-card"
						class="avatar-uploader"
						:headers="headers"
					>
						<a href="javascript:;" v-if="imageUrl" :src="imageUrl" class="card-pic">
							<img :src="imageUrl" alt="avatar" style="max-width:86px;" />
							<!-- <span class="ant-upload-list-item-actions"><a-icon type="eye" /></span> -->
						</a>
						<div v-else>
							<a-icon :type="loading ? 'loading' : 'plus'" />
							<div class="ant-upload-text">上传封面</div>
						</div>
					</a-upload>
				</a-form-item>
				<a-form-item label="活动图片">
					<a-upload
						v-decorator="[
							'picList',
							{
								valuePropName: 'fileList',
								getValueFromEvent: normPicListFile,
								rules: [{ required: true, message: '活动图片' }]
							}
						]"
						name="file"
						:action="uploadFile"
						:multiple="true"
						list-type="picture-card"
						class="avatar-uploader"
						:headers="headers"
					>
						<div>
							<a-icon type="plus" />
							<div class="ant-upload-text">上传活动图片</div>
						</div>
					</a-upload>
				</a-form-item>
			</a-form>
		</a-spin>
	</a-modal>
</template>

<script>
function getBase64(file) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result);
		reader.onerror = error => reject(error);
	});
}
import { api } from '@/api/index.js';
import { ModalMixins } from '@/mixins';
import JDate from '@/components/JDate.vue';
export default {
	name: 'addActivityModal',
	mixins: [ModalMixins],
	data() {
		return {
			uploadFile: process.env.VUE_APP_API_BASE_URL + api.uploadFile,
			loading: false,
			loadingMusic: false, //是否正在上传音乐
			headers: {
				'X-AUTH-TOKEN': 'Basic ' + window.localStorage.getItem('token')
			},
			imageUrl: '',
			musicUrl: ''
		};
	},
	created() {},
	components: { JDate },
	methods: {
		add(record) {
			this.visible = true;
			if (record) {
				this.title = '编辑活动';
				this.isAdd = false;
				this.mdl = { ...record };
				this.getActivityDetail(record.id);
			} else {
				this.title = '新增活动';
				this.isAdd = true;
			}
		},
		init() {
			this.$nextTick(() => {
				this.form.setFieldsValue(this.$pick(this.mdl, 'activityName', 'telPhone', 'musicUrl', 'coverImg', 'activityTime', 'picList'));
			});
		},
		getActivityDetail(id) {
			this.$postAction(api.getActivityDetail, {
				id
			})
				.then(res => {
					if (res.result) {
						let activityTime = [moment(res.data.startTime) || undefined, moment(res.data.endTime) || undefined];
						let picList = res.data.picList.map(item => {
							return {
								uid: item.id,
								status: 'done',
								name: 'image.png',
								url: this.filebaseUrl + item.picUrl
							};
						});
						this.mdl = {
							...this.mdl,
							...res.data,
							activityTime,
							picList
						};
						this.imageUrl = this.filebaseUrl + res.data.coverImg;
						this.musicUrl = res.data.musicUrl;
						this.init();
					}
				})
				.finally(() => {
					this.confirmLoading = false;
				});
		},
		close() {
			this.form.resetFields();
			this.imageUrl = '';
			this.musicUrl = '';
			this.confirmLoading = false;
			this.loading = false;
			this.loadingMusic = false;
			this.$emit('close');
			this.visible = false;
		},
		handleOk() {
			const _this = this;
			// 触发表单验证
			this.form.validateFields((err, values) => {
				console.log('values', values);
				// 验证表单没错误
				if (!err) {
					let { activityName, musicUrl, coverImg, telPhone } = values;
					let parameter = {
						activityName,
						musicUrl,
						coverImg,
						telPhone,
						startTime: moment(values.activityTime[0]).format('YYYY-MM-DD'),
						endTime: moment(values.activityTime[1]).format('YYYY-MM-DD'),
						picList: values.picList.map(item => item.url.replace(this.filebaseUrl, ''))
					};
					_this.confirmLoading = true;
					this.$postAction(api.addActivity, Object.assign({}, parameter, !this.isAdd ? { id: this.mdl.id } : null))
						.then(res => {
							if (res.result) {
								_this.$message.success('保存成功');
								_this.$emit('ok');
								_this.form.resetFields();
								_this.visible = false;
							}
						})
						.finally(() => {
							_this.confirmLoading = false;
						});
				}
			});
		},
		handleCancel() {
			this.close();
		},
		normFile(e) {
			if (Array.isArray(e)) {
				return e;
			}
			if (e.file.status === 'uploading') {
				this.loading = true;
				return;
			}
			if (e.file.status === 'done') {
				getBase64(e.file.originFileObj).then(imageUrl => {
					this.imageUrl = imageUrl;
					this.loading = false;
				});
			}
			return e && e.file && e.file.response && e.file.response.data ? e.file.response.data.url : null;
		},
		normMusiFile(e) {
			if (Array.isArray(e)) {
				return e;
			}
			if (e.file.status === 'uploading') {
				this.loadingMusic = true;
				return;
			}
			let fileUrl = e && e.file && e.file.response && e.file.response.data ? e.file.response.data.url : null;
			if (e.file.status === 'done') {
				if (e.file.type == 'audio/mpeg') {
					this.musicUrl = fileUrl;
					this.loadingMusic = false;
				}
			}
			return fileUrl;
		},
		normPicListFile(e) {
			if (Array.isArray(e)) {
				return e;
			}
			if (e && e.fileList) {
				e.fileList.forEach(item => {
					let fileUrl = item.response && item.response.data ? item.response.data.url : null;
					if (!item.url && fileUrl) {
						item.url = fileUrl;
					}
				});
			}
			return e && e.fileList;
		}
	}
};
</script>

<style scoped lang="less">
.card-pic {
	position: relative;
	display: block;
	.ant-upload-list-item-actions {
		background: rgba(0, 0, 0, 0.5);
		opacity: 0;
		-webkit-transition: all 0.3s;
		transition: all 0.3s;
		position: absolute;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		display: block;
		.anticon {
			position: absolute;
			top: 50%;
			left: 50%;
			z-index: 10;
			white-space: nowrap;
			-webkit-transform: translate(-50%, -50%);
			transform: translate(-50%, -50%);
			color: #fff;
			font-size: 16px;
		}
	}
	&:hover .ant-upload-list-item-actions {
		opacity: 1;
	}
}
</style>
